/*
 * This file is part of din.
 *
 * din is copyright (c) 2006 - 2012 S Jagannathan <jag@dinisnoise.org>
 * For more information, please visit http://dinisnoise.org
 *
 * din is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * din is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with din.  If not, see <http://www.gnu.org/licenses/>.
 *
*/
#ifndef __vector2d
#define __vector2d
#include <math.h>
template <class T> inline T distance2 (const T& x1, const T& y1, const T& x2, const T& y2) {
  T dx = x2 - x1;
  T dy = y2 - y1;
  return (dx * dx + dy * dy);
}

template<class T> inline void direction (T& dx, T& dy, const T& x1, const T& y1, const T& x2, const T& y2) {
  dx = x2 - x1;
  dy = y2 - y1;
}

template <class T> inline double magnitude (const T& x1, const T& y1, const T& x2, const T& y2) {
  T dx, dy;
  direction (dx, dy, x1, y1, x2, y2);
  return sqrt ((double) (dx * dx + dy * dy));

}

template <class T> inline double magnitude (const T& vx, const T& vy) {
  return sqrt ((double) (vx * vx + vy * vy));

}

template <class T> inline double magnitude2 (const T& x1, const T& y1, const T& x2, const T& y2) {
  T dx, dy;
  direction (dx, dy, x1, y1, x2, y2);
  return (dx * dx + dy * dy);

}

template <class T> inline T magnitude2 (const T& vx, const T& vy) {
  return (vx * vx + vy * vy);
}


template<class S, class T> inline double unit_vector (S& ux, S& uy, const T& x1, const T& y1, const T& x2, const T& y2) {

  // unit vector joining x1,y1 & x2,y2
  T dx, dy; direction (dx, dy, x1, y1, x2, y2);
  double mag = magnitude (dx, dy);
  if (mag > 0) {
    ux = dx / mag;
    uy = dy / mag;
  } else {
    ux = uy = 0;
  }
  return mag;
}

template <class T> inline double unit_vector (T& ux, T& uy, const T& vx, const T& vy) {


  double mag = magnitude (vx, vy);
  if (mag > 0) {
    ux = vx / mag;
    uy = vy / mag;
  } else {
    ux = uy = 0;
  }

  return mag;

}

#endif
